package com.gpipe.tools;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import org.apache.log4j.Logger;

import java.io.*;
import java.sql.*;
import java.util.*;

public class TrafficParse {
	private static Logger logger = Logger.getLogger(TrafficParse.class);

	private String big_area = "large.geojson";// 交通大区划分配置（json）
	private String mid_area = "mid.geojson";// 交通中区划分配置（json）
	private String sma_area = "";// 交通小区划分配置（json）
	private String bts_conf = "";// 广州基站配置（按照规定格式提供）
	private String path = "D:\\test\\traffic_area\\";// 配置文件根目录
	
	Tools tools = new Tools();
	
	/*
	 * 功能：根据文件命选择对应的文件解析器，返回hashmap{traffic_area_name/id|longitude,latitude}
	 */
	private HashMap<BigArea, List> readInMap(String fileName, String fileFlag) throws IOException {
		String filePath = tools.getFilePath(path, fileName);

		int preSize = 400 * 1024 * 1024;// 读入的数据块大小
		StringBuffer fileStr = new StringBuffer();

		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
		BufferedReader in = new BufferedReader(new InputStreamReader(bis, "utf-8"), preSize);// 10M缓存
		while (in.ready()) {
			fileStr.append(in.readLine());
		}
		if (fileFlag.toLowerCase().equals("txt")) {

		} else if (fileFlag.toLowerCase().equals("json")) {
			return processJSON(fileStr);

		} else {
			logger.error("属于不支持的文件类型");
		}
		return null;
	}
	
	/*
	 * 功能：读取对应表的数据，写入，返回hashmap{traffic_area_name/id|longitude,latitude}
	 */
	public List<SignalBts> readMysql(String tableName) {
		List<SignalBts> lists = new ArrayList<SignalBts>();

		Connection conn = null;
		try {
			conn = returnconn("127.0.0.1","signaldb","root","123567");
		// statement用来执行SQL语句
        Statement statement = conn.createStatement();
        // 要执行的SQL语句
        String sql = "select * from "+tableName;
        // 结果集
        ResultSet rs = statement.executeQuery(sql);

        while(rs.next()) {
			SignalBts signalBts = new SignalBts();
			signalBts.initSignalBts(rs.getString("LAC"),rs.getString("CI"),rs.getString("ADM_AREA"),rs.getString("BTS_NAME"),rs.getString("LONGITUDE"),rs.getString("LATITUDE"));
            lists.add(signalBts);
        }
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("数据库连接有误或者sql语句有误");
		}

		return lists;
	}
	
	private Connection returnconn(String ip,String db,String user,String password) throws ClassNotFoundException, SQLException {
		// 驱动程序名
        String driver = "com.mysql.jdbc.Driver";
        // URL指向要访问的数据库名scutcs
        String url = "jdbc:mysql://"+ip+":3306/"+db+"?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8";
         // 加载驱动程序
         Class.forName(driver);
         // 连续数据库
         Connection conn = DriverManager.getConnection(url, user, password);
         return conn;
	}

	// process
	private void processTXT(StringBuffer fileStr) throws IOException {
	}

	// process
	/*
	 * 功能：根据具体的json格式来解析，返回hashmap
	 */
	private HashMap<BigArea, List> processJSON(StringBuffer fileStr) throws IOException {
		HashMap<BigArea, List> resultMap = new HashMap<BigArea, List>();
		String flag = "features";
		String flag1 = "properties";
		String flag2 = "geometry";
		String flag3 = "coordinates";

		
		String mapValue = "";
		List listResult = new ArrayList<>();

		
		String val = tools.getJSONelement(fileStr.toString(), flag);
//		logger.info("features=" + val);
		JsonArray val1 = tools.getJsonArray(val);
		for (JsonElement jo : val1) {
			BigArea mapKey = new BigArea();
			mapKey.init(tools.getJSONelement(jo.toString(), flag1));
//			logger.info("mapKey="+mapKey.getName()+"|"+mapKey.getId());
			
			
			mapValue = tools.getJSONelement(tools.getJSONelement(jo.toString(), flag2), flag3);
			
//			JsonArray val2 = tools.getJsonArray(mapValue);
			
			listResult = tools.parseStrToList(mapValue);
			
			
//			logger.info(mapKey.getName()+"|"+val2.toString());
			
			resultMap.put(mapKey, listResult);
		}
		return resultMap;

	}

	/**
	 * 功能：关联交通区和信令基站的程序入口。
	 */
	private void entrance() throws IOException {
		logger.info("info");
		logger.debug("debug");
		logger.error("error");

		//结果数据
		List<TrafficAndSignal> result = new ArrayList<TrafficAndSignal>();

		//交通区的HashMap
		HashMap<BigArea, List> trafficAreaMap = readInMap("small_area.geojson", "json");

		//广州信令的配置
		List<SignalBts> signalConfs= readMysql("base_conf_gz_zrx");
		//两者融合
		PointIsIn toolPoint = new PointIsIn();

		for(SignalBts signalConf:signalConfs){
			TrafficAndSignal tas = new TrafficAndSignal();
			logger.info("##"+signalConf.getBtsName()+"|"+signalConf.getPoint().print());
			Iterator<Map.Entry<BigArea, List>> iter = trafficAreaMap.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry<BigArea, List> entry = (Map.Entry<BigArea, List>) iter.next();
				BigArea key = entry.getKey();
				List val = entry.getValue();

				//一层：[point,point,point,point,point]
				//多层：[[point,point],[point,point]]
				for(Object ob:val){
					if(ob instanceof Point){
						logger.info("交通区配置为一层，交通区为："+key.getName()+"|"+key.getId());
						if(toolPoint.isIn(signalConf.getPoint(),val).equals("1")){
							tas.initTrafficAndSignal(key.getId(), key.getName(),signalConf.getLac(),signalConf.getCi(),signalConf.getBtsName());
							result.add(tas);
						};
						break;
					}else{
						logger.info("交通区配置为多层，交通区为："+key.getName()+"|"+key.getId());
						if(toolPoint.isIn(signalConf.getPoint(), (List<Point>) ob).equals("1")){
							tas.initTrafficAndSignal(key.getId(), key.getName(),signalConf.getLac(),signalConf.getCi(),signalConf.getBtsName());
							result.add(tas);
							break;
						};
					}
				}
			}
		}
		System.out.println("small_area and signal 's result's size="+result.size());
		logger.info("small_area and signal 's result's size="+result.size());

		//写入mysql
		Connection conn = null;
		int batchSize = 50000;
		int count = 5000000;

		try {
			conn = returnconn("127.0.0.1","signaldb","root","123567");
			conn.setAutoCommit(false);
			PreparedStatement ps = conn.prepareStatement("insert into base_area_conf_small_signal (small_id,small_name,lac,ci,bts_name) values (?,?,?,?,?)");
			int i = 1;
			for(TrafficAndSignal tas :result){
//			for (long i = 1; i < count; i++) {
				i++;
				ps.setString(1,tas.getSmall_id());//设置第一个参数的值为i
				ps.setString(2,tas.getSmall_name());
				ps.setString(3,tas.getLac());
				ps.setString(4,tas.getCi());
				ps.setString(5,tas.getBts_name());

				ps.addBatch();//将该条记录添加到批处理中
				if (i% batchSize == 0) {
					ps.executeBatch();//执行批处理
					conn.commit();//提交
				}
			}
			if ((count+1) % batchSize != 0) {
				ps.executeBatch();
				conn.commit();
			}
			ps.close();

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}


	}


	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		TrafficParse tt = new TrafficParse();
		tt.entrance();




//		HashMap<BigArea, List> aa = tt.readInMap("larger_area.geojson", "json");
//
//		System.out.println("wait");

		
//		tt.readMysql("base_conf_gz_zrx");
		
		
	}

}
